package com.wswy.wzcx.ui.fkdj

import android.Manifest
import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.TextUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.che.libcommon.utils.ToastUtils
import com.google.zxing.activity.CaptureActivity
import com.google.zxing.util.QrConstant
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.R
import com.wswy.wzcx.api.ConfigsKt
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.dialog.LongtimeLoadingDialog
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.ui.other.FineNoTextWatcher
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import com.wswy.wzcx.ui.web.WebViewActivity
import com.wswy.wzcx.utils.StringUtils
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_fkdj_pre.*
import timber.log.Timber

@Deprecated("")
class FinePreFragment : CBaseFragment() {

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_fkdj_pre
    }

    private lateinit var fineViewModel: FineViewModel


    private var dialog:LongtimeLoadingDialog?=null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        fineViewModel = provideViewModelFromActivity(FineViewModel::class.java)

        et_fine_no.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(19))

        et_fine_no.addTextChangedListener(FineNoTextWatcher(et_fine_no))
        et_fine_no.addTextChangedListener(object : TextWatcherIMPL() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                if (TextUtils.isEmpty(s)) {
                    //为空 扫描
                    img_input.setImageResource(R.drawable.scanning)
                    //fl_no_clear.visibility = View.INVISIBLE
                } else {
                    //不为空 删除
                    img_input.setImageResource(R.drawable.ic_clean)
                    //fl_no_clear.visibility = View.VISIBLE
                }
            }
        })

        fineViewModel.getLastFineNo()?.let {
            kotlin.runCatching {
                et_fine_no.setText(it)

                et_fine_no.setSelection(et_fine_no.text?.length?:0)
            }

        }



        fl_no_clear.onClick {
            //
            if (TextUtils.isEmpty(et_fine_no.text)){
                //扫描

                RxPermissions(this).request(Manifest.permission.CAMERA).singleOrError()
                        .subscribe(object : SingleObserver<Boolean>{
                            override fun onSuccess(t: Boolean) {
                                if (t){
                                    val intent = Intent(requireContext(), CaptureActivity::class.java).apply {
                                        putExtra(QrConstant.CONFIG_TITLE,"扫描处罚决定书编号")
                                    }
                                    startActivityForResult(intent, QrConstant.REQ_QR_CODE)
                                }else{
                                    ToastUtils.showText("没有权限")
                                }
                            }

                            override fun onSubscribe(d: Disposable) {

                            }

                            override fun onError(e: Throwable) {
                                ToastUtils.showText(e.message)
                            }

                        })



            }else{
                //删除
                et_fine_no.text = null
                fineViewModel.saveFineNo(null)
            }

        }

        tv_no_hint.onClick {
            DialogFactory.showHelp(it.context,R.drawable.chujuebianma)
        }

        tv_issue.onClick {
            WebViewActivity.startWebview(it.context, ConfigsKt.H5_CJWT_FKDJ())
        }

        var login = false

        ll_btn_next.onClick {

            val no = FineNoTextWatcher.getRealFineNumber(et_fine_no)
            login = false
            if (fineViewModel.checkFineNo(no)){

                if (fineViewModel.hasLogin()){
                    fineViewModel.checkFine(no!!)
                    ll_btn_next.isClickable = false

                }else{

                    fineViewModel.gotoLogin(it.context)
                    login = true
                }


            }
        }

        //填充默认处罚决定书单号
        arguments?.getString(Constants.EXTRA_DATA)?.let {
            et_fine_no.setText(it)
            et_fine_no.setSelection(et_fine_no.text?.length?:0)
        }

        fineViewModel.getUserLiveData().observe(this, Observer {
            it?.run {

                val no = FineNoTextWatcher.getRealFineNumber(et_fine_no)
                if (login && fineViewModel.checkFineNo(no)){
                    fineViewModel.checkFine(no!!)
//                    et_fine_no.isEnabled = false
//                    ll_btn_next.isClickable = false
                }
            }
        })


        fineViewModel.getCheckFineLiveData().observe(this, Observer {


            it?.run {

                if (inLoading()){


                    showLoading()

                }else{
                    dialog?.dismiss()
                    ll_btn_next.isClickable = true
//                    et_fine_no.isEnabled = true

                }

            }

        })

    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if(!hidden){
            ll_btn_next.isClickable = true
        }
    }

    private fun showLoading(){

        dialog?.dismiss()


        dialog = LongtimeLoadingDialog(context).also {
            it.show()
        }

        KeyboardUtils.hideSoftInput(et_fine_no)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == QrConstant.REQ_QR_CODE){
            val scanResult = data?.extras?.getString(QrConstant.INTENT_EXTRA_KEY_QR_SCAN)

            Timber.e("result -->  $scanResult")
            if(StringUtils.isNum(scanResult)){
                et_fine_no.setText(scanResult)
                et_fine_no.setSelection(et_fine_no.text?.length?:0)
            }


        }

    }

    override fun onDestroy() {
        super.onDestroy()
        dialog?.dismiss()
    }

}